package com.appkubes.mall.admin.application.plugin.plugin.controller;

import com.appkubes.cloud.config.params.paramValid.ParamValid;
import com.appkubes.common.Response;
import com.appkubes.common.exception.BusinessException;
import com.appkubes.mall.admin.application.plugin.plugin.entity.vo.PluginAddVO;
import com.appkubes.mall.admin.application.plugin.plugin.service.PluginService;
import com.appkubes.mall.admin.application.system.plugin.entity.dto.SystemPluginDTO;
import com.appkubes.mall.admin.application.system.plugin.entity.vo.GetPluginVO;
import com.appkubes.mall.admin.application.system.plugin.service.SystemPluginService;
import com.appkubes.mall.core.entity.MallPlugin;
import com.appkubes.mall.core.entity.MallSystemPlugin;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: Rongjie
 * @Date: 2020/1/15 23:09
 * @Description:
 */

@Api("插件模块")
@RestController
@RequestMapping("/plugin")
public class PluginController {
    @Resource
    PluginService pluginService;

    @Resource
    SystemPluginService systemPluginService;

    @ApiOperation("获取已开通插件")
    @GetMapping("/get")
    public Response get(@ParamValid GetPluginVO getPluginVO) {
        MallSystemPlugin entity = new MallSystemPlugin();
        entity.setPluginType(getPluginVO.getPluginType());

        List<MallSystemPlugin> pluginList = systemPluginService.selectListByEntity(entity);

        List<SystemPluginDTO> resultList = new ArrayList<>();
        for (MallSystemPlugin mallSystemPlugin : pluginList) {
            SystemPluginDTO pluginDTO = new SystemPluginDTO();
            BeanUtils.copyProperties(mallSystemPlugin, pluginDTO);

            //检查系统是否已经开通过了
            MallPlugin plugin = pluginService.getPlugin(getPluginVO.getAppKey(), mallSystemPlugin.getPluginCode());
            Integer isOpen = plugin == null ? 0 : 1;
            pluginDTO.setIsOpen(isOpen);
            if (pluginDTO.getIsOpen() == 1) {
                resultList.add(pluginDTO);
            }
        }
        return Response.success(resultList);
    }

    @ApiOperation("开通插件")
    @GetMapping("/add")
    Response add(@Valid PluginAddVO pluginAddVO, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return Response.error("参数检查失败");
        }

        try {
            MallPlugin plugin = pluginService.addPlugin(pluginAddVO);
            return Response.success(plugin);
        } catch (BusinessException be) {
            //TODO 优化代码
            return Response.error(be.getMessage());
        }
    }
}
